import json
import re
import sys


def is_chinese_str(text):
    # 使用正则表达式匹配日文平假名和片假名
    japanese_kana_pattern = re.compile("[\u3040-\u309F\u30A0-\u30FF]")

    # 检查字符串是否包含日文平假名和片假名
    is_japan = bool(japanese_kana_pattern.search(text))
    if is_japan:
        return False

    for ch in text:
        # 中文字符
        if "\u4e00" <= ch <= "\u9fff":
            return True

    return False


class DataBase:
    """
    从离线数据库中，初始化数据，提供查询接口。
    """

    def __init__(self) -> None:
        self.jobj = json.load(open("anime_db.json"))
        self.data = self.jobj["data"]

    def search(self, name):
        if is_chinese_str(name):
            return name

        for item in self.data:
            synonyms = item["synonyms"]
            if name not in synonyms:
                continue
            for sm in synonyms:
                if is_chinese_str(sm):
                    print(item)
                    return sm

        return self.search2(name)

    def search2(self, name):
        if is_chinese_str(name):
            return name
        for item in self.data:
            synonyms = " - ".join(item["synonyms"]).lower()
            if name.lower() not in synonyms:
                continue
            for sm in item["synonyms"]:
                if is_chinese_str(sm):
                    print(item)
                    return sm


if __name__ == "__main__":
    db = DataBase()
    # print(db.search("火影忍者"))
    # print(db.search("スパイ教室"))
    # print(db.search("呪術廻戦"))
    # print(db.search("You-Zitsu 3"))
    # print(db.search("Eiyuuou, Bu wo Kiwameru Tame Tenseisu"))
    # print(db.search("Jigokuraku"))
    # print(db.search("kono subarashii sekai ni bakuen o!"))  # 单词都是错误的！
    if len(sys.argv) != 2:
        exit
    print(db.search(sys.argv[1]))
